package ias.deepsearch.com.helper.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.socks.library.KLog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import ias.deepsearch.com.helper.R;
import ias.deepsearch.com.helper.model.dp.AppInfo;
import ias.deepsearch.com.helper.ui.adapter.MyAppInfoRecyclerViewAdapter;
import ias.deepsearch.com.helper.ui.view.SpaceItemDecoration;
import ias.deepsearch.com.helper.util.net.EngineUpdater;
import ias.deepsearch.com.helper.util.normal.Constants;
import ias.deepsearch.com.helper.util.normal.FileUtil;
import ias.deepsearch.com.helper.util.normal.Utils;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


public class AppEnableFragment extends Fragment implements MyAppInfoRecyclerViewAdapter.OnItemCheckedListener{

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;

    RecyclerView recyclerView;

    EngineUpdater engineUpdater;

    MyAppInfoRecyclerViewAdapter myAdapter;



    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public AppEnableFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static AppEnableFragment newInstance(int columnCount) {
        AppEnableFragment fragment = new AppEnableFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_appinfo_list, container, false);
        engineUpdater = new EngineUpdater(getActivity(), this);
        myAdapter = new MyAppInfoRecyclerViewAdapter(getActivity(), null, AppEnableFragment.this);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }

            recyclerView.addItemDecoration(new SpaceItemDecoration(6));
            recyclerView.setAdapter(myAdapter);
            getAppsInstalled();
        }
        return view;
    }


    List<AppInfo> getAppInfo(){
        List<AppInfo> appInfoList = Utils.getAppListInfo(getActivity());
        List<String> localEngines = FileUtil.getLocalEngines();
        for(int i = 0; i < appInfoList.size(); i++){
            String package_name = appInfoList.get(i).packageName;
            String md5 = FileUtil.getApkMD5(package_name);
            appInfoList.get(i).md5 = md5;
            if(localEngines.contains(md5+".dex")){
                KLog.v("liuyi", appInfoList.get(i).appName + " has local engine");
                appInfoList.get(i).hasKnowledge = true;
                File file = new File(Constants.LOCAL_ENGINE_PATH + "/" + md5+".dex");
                Long time =file.lastModified();
                String formatTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time));
                appInfoList.get(i).knowledgeUpdateTime = formatTime;

            }else{
                appInfoList.get(i).knowledgeUpdateTime = "无";
            }
        }
        return appInfoList;
    }

    //获取本地安装的apk列表
    void getAppsInstalled(){

        Observable.create(new Observable.OnSubscribe<List<AppInfo>>() {
            @Override
            public void call(Subscriber<? super List<AppInfo>> sub){
                sub.onNext(getAppInfo());
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<AppInfo>>() {
                    @Override
                    public void call(List s) {
                        myAdapter.update(s);
                    }
                });

    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onItemChecked(int position, AppInfo item) {
        engineUpdater.updateEngine(position, item.appName, item.md5);
    }

    @Override
    public void onItemChanged(int position, boolean checked) {
        myAdapter.checked(position, checked);
    }

    @Override
    public void onItemClick(int i, AppInfo appInfo) {
        AppManagementFragment dialog = new AppManagementFragment();
        Bundle bundle = new Bundle();
        bundle.putString("appInfo", new Gson().toJson(appInfo));
        dialog.setArguments(bundle);
        dialog.show(getFragmentManager(), appInfo.appName);
    }
}
